<?php
/*
* @desc 用户登录注册管理
* @author kevin.wang
* @date 2015-01-01 12:00:00
**/
class PassportController extends Controller
{
	public  $layout = '/layouts/base';
	//过滤器
	public function filters()
    {
        return array(
            'UserLogin + register, login',
        );
    }
	//用户注册功能
	public function actionRegister()
	{
		if(!Yii::app()->request->isPostRequest){
			$this->render('index', array('method' => 'register'));
			Yii::app()->end();
		}
		//用户注册
		$data = array('status' => 0, 'body' => array());
		$registerForm = Yii::app()->request->getParam("registerForm");
		$model = new RegisterForm;
		$model->attributes = $registerForm;
		if(!$model->validate() || !$model->register()){
			$msg = array_values($model->getErrors());
			$data['status'] = 10000;
			$data['msg'] = $msg[0];
			$this->renderJson($data);
		}
		$autologin = array(
				'username' =>$registerForm['username'],
			    'rememberMe' =>0,
			    'password' =>$registerForm['password'],
			);
		$model = new LoginForm;
		$model->attributes = $autologin;
		$model->login();
		$data['body']['returnUrl'] = Yii::app()->createUrl("passport/success");
		$this->renderJson($data);
	}
	//成功注册页面
	public function actionSuccess()
	{
		$this->render("success");
	}
	//用户登录功能
	public function actionLogin()
	{
		if(!Yii::app()->request->isPostRequest){
			$this->render('index', array('method' => 'login'));
			Yii::app()->end();
		}
		$data = array('status' => 0, 'body' => array());
		$model = new LoginForm;
		$model->attributes = Yii::app()->request->getParam("loginForm");
		if(!$model->validate() || !$model->login()){
			$msg = array_values($model->getErrors());
			$data['status'] = 10000;
			$data['msg'] = $msg[0];
			$this->renderJson($data);
		}
		$returnUrl = Yii::app()->session['rturnUrl'];
		$data['body']['returnUrl'] = empty($returnUrl)?Yii::app()->user->returnUrl:$returnUrl;
		unset(Yii::app()->session['rturnUrl']);
		$this->renderJson($data);
	}
	//用户退出功能
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	//用户登录过滤
	function filterUserLogin($filterChain){
		$model = new LoginForm();
		$result = $model->userIsLogin();
		if(!empty($result)){
			$this->redirect(Yii::app()->createUrl("user/index"));
		}
		$filterChain->run();
	}
}
